package com.wskj.shiro.chapter3.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import com.wskj.shiro.chapter3.permission.BitPermission;

/***
 * 此时我们继承AuthorizingRealm而不是实现Realm接口；推荐使用AuthorizingRealm，因为：
 * 
 * AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken
 * token)：表示获取身份验证信息；
 * 
 * AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection
 * principals)：表示根据用户身份获取授权信息。 这种方式的好处是当只需要身份验证时只需要获取身份验证信息而不需要获取授权信息。
 * 对于AuthenticationInfo和AuthorizationInfo请参考其Javadoc获取相关接口信息。
 * 
 * @author Administrator
 *
 */
public class MyRealm extends AuthorizingRealm {

	/**
	 * 获取用户的授权的信息 
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addRole("role1");
		authorizationInfo.addRole("role2");
		authorizationInfo.addObjectPermission(new BitPermission("+user1+10"));
		authorizationInfo.addObjectPermission(new WildcardPermission("user1:*"));
		authorizationInfo.addStringPermission("+user2+10");
		authorizationInfo.addStringPermission("user2:*");
		return authorizationInfo;
	}
	
	
	
	
    /**
     * 获取用户的身份信息
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		
		// 判断用户名和密码 	
		String username =(String) token.getPrincipal();//用户名称
		String password=new String((char[]) token.getCredentials());//用户的密码
		
		if(!"zhang".equals(username)) {  
            throw new UnknownAccountException(); //如果用户名错误  
        }  
        if(!"123".equals(password)) {  
            throw new IncorrectCredentialsException(); //如果密码错误  
        }          
        //如果身份认证验证成功，返回一个AuthenticationInfo实现；		
		return new SimpleAuthenticationInfo(username, password, getName());
		
	}

}
